<?php
namespace app\modules\frontend\models;
use yii\base\Model;

class ContentSearch extends Content
{
    public $catids_by_tag;//根据TAG查出的catid(多个)
    public $begin_time;
    public $end_time;
    public $sort_flag;//排序方式 0-默认 1-预览总数正序 2-预览总数倒序

    public function rules()
    {
        return [
            ['app_id', 'required', 'message' => 'app_id不能为空'],
            ['catids_by_tag', 'string', 'message' => 'catids_by_tag必须是字符串'],
            ['title', 'default', 'value' => ''],
            ['title', 'string', 'message' => 'title必须是字符串',
                             'max' => 32, 'tooLong' => 'title最长32位'],
            ['member_view', 'default', 'value' => 0],
            ['member_view', 'integer', 'message' => 'member_view必须为数字，或数字字符串'],
            ['member_view', 'in', 'range' => array(0, 1, 2), 'message' => 'member_view值必须在0~2中选择'],
            ['begin_time', 'date', 'format'=>'yyyy-MM-dd', 'message' => 'begin_time非yyyy-MM-dd格式'],
            ['end_time', 'date', 'format'=>'yyyy-MM-dd', 'message' => 'end_time非yyyy-MM-dd格式'],
            ['sort_flag', 'default', 'value' => 0],
            ['sort_flag', 'integer', 'message' => 'sort_flag必须为数字，或数字字符串'],
            ['sort_flag', 'in', 'range' => array(0, 1, 2), 'message' => 'sort_flag值必须在0~2中选择'],

        ];
    }

    public function scenarios()
    {
        return Model::scenarios();
    }

    public function search($params, $appid)
    {
        $data['ContentSearch'] = $params;
        $data['ContentSearch']['app_id'] = $appid;
        // P($data);

        $query = Content::find();

        if (!($this->load($data) && $this->validate())) {
            return false;
        }
        // P($this);

        if(isset($this->catids_by_tag)){
            $query -> orFilterWhere(
                ['in', '{{%content}}.content_id', explode(',', $this->catids_by_tag)]
            );
        }


        if(isset($this->title)){
            $query -> andFilterWhere(
                ['like', '{{%content}}.title', $this->title]
            );
        }


        if($this->member_view > 0){
            $query -> andFilterWhere([
                'member_view' => $this->member_view,
            ]);
        }


        if(isset($this->end_time) and !empty($this->end_time)){
            $this->end_time .= ' 23:59:59';
        }
        $query -> andFilterWhere(['>=', '{{%content}}.add_time', $this->begin_time])
               -> andFilterWhere(['<=', '{{%content}}.add_time', $this->end_time]);


        return $query;
    }

    
}